package login;
import hibernateUtil.Userinfo;
import hibernateUtil.UserinfoDao;
import io.ClientSession;
import io.OperationResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import platform.AppConfig;
import platform.Platform;
import protocol.ReturnCode;
import protomsg.Result.ServerResFlag;
import sun.util.logging.resources.logging;
import MemoryDB.YuanTable;
import Public.GameScheduleType;
import Public.PublicFunction;


public class Util {
	protected static final Logger log = LoggerFactory.getLogger(Util.class);

//	static UserinfoDao info = new UserinfoDao();
	
	 private static ObjectMapper objectMapper = new ObjectMapper();
	    static{
	    	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
	      	objectMapper.setDeserializationConfig(objectMapper.getDeserializationConfig().without(                  
	    		       DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES));
	    }
	
		public static Object decodeJson(String json, Class pojoClass) throws Exception{		
			try{
				return objectMapper.readValue(json, pojoClass);
			}catch(Exception e){
				throw e;
			}
		}
		
		public static String encodeJson(Object o) throws Exception{
			try{
				return objectMapper.writeValueAsString(o);
			}catch(Exception e){
				throw e;
			}
		}
     public static String doPost(String url, String body) { 
    	 StringBuffer stringBuffer = new StringBuffer();
			HttpEntity entity = null;
			BufferedReader in = null;
			HttpResponse response = null;
			try {
				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpParams params = httpclient.getParams();
				HttpConnectionParams.setConnectionTimeout(params, 20000);
				HttpConnectionParams.setSoTimeout(params, 20000);
				HttpPost httppost = new HttpPost(url);
				httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");

				httppost.setEntity(new ByteArrayEntity(body.getBytes("UTF-8")));
				response = httpclient.execute(httppost);
				entity = response.getEntity();
				in = new BufferedReader(new InputStreamReader(entity.getContent()));
				String ln;
				while ((ln = in.readLine()) != null) {
					stringBuffer.append(ln);
					stringBuffer.append("\r\n");
				}
				httpclient.getConnectionManager().shutdown();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (IllegalStateException e2) {
				e2.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (null != in) {
					try {
						in.close();
						in = null;
					} catch (IOException e3) {
						e3.printStackTrace();
					}
				}
			}
			return stringBuffer.toString();
    } 
     

    public static String getMD5Str(String str) {  
        MessageDigest messageDigest = null;  
  
        try {  
            messageDigest = MessageDigest.getInstance("MD5");  
  
            messageDigest.reset();  
  
            messageDigest.update(str.getBytes("UTF-8"));  
        } catch (NoSuchAlgorithmException e) {  
            System.out.println("NoSuchAlgorithmException caught!");  
            System.exit(-1);  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
  
        byte[] byteArray = messageDigest.digest();  
  
        StringBuffer md5StrBuff = new StringBuffer();  
  
        for (int i = 0; i < byteArray.length; i++) {              
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)  
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));  
            else  
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));  
        }  
  
        return md5StrBuff.toString();  
    }  
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	log.info("util sendget锟斤拷锟斤拷锟斤拷锟斤拷锟届常锟斤拷"+e.toString());
            e.printStackTrace();
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        if(result.equals("")){
        	log.info("util sendget锟斤拷锟斤拷result锟斤拷锟街匡拷值锟斤拷锟斤拷锟杰碉拷锟铰的斤拷锟斤拷锟酵拷锟斤拷频锟铰硷拷锟绞�,result 锟斤拷锟斤拷锟�=锟斤拷"+result);
        }
        return result;
    }
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    

    public static short sdkReceived(OperationResponse operationRequest,ClientSession session,String id,String deviceID,String isGetIP,String sdk,String PhoneType,String pwd){
    	
    	short returnCode = ServerResFlag.No_VALUE;
    	YuanTable dt = Platform.getServiceManager().getDbService().userinfoDao.GetUserinfoForTableByUid(id);
		if (dt != null && dt.getRows().size() > 0) {
//			OperationResponse response = new OperationResponse(
//					operationRequest.OperationCode,
//					AppConfig.dicAppInfo, ReturnCode.Yes, "");
			
			returnCode = ServerResFlag.ACCOUNTREPEAT_VALUE;
//			session.SendOperationResponse(response);
	

			PublicFunction.SetPlayerBehaviorPass(ConsumptionType.Online,
					session.getClientIP(), id);
			PublicFunction.SetPlayerBehaviorPass(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
					ConsumptionType.GameSchedule,
					GameScheduleType.Logon.toString(), id);
			
			if (isGetIP.equals("1")) {
				String[] strIP = dt.getRows().get(0).getItem("loginIP")
						.toString().trim().split("[;]", -1);
				ArrayList<String> listIP = new ArrayList<String>();
				for (String str : strIP) {
					if (!str.equals("")) {
						listIP.add(str);
					}

				}
				if (listIP.size() >= 10) {
					listIP.remove(0);
					listIP.add(session.getClientIP());

				} else {
					listIP.add(session.getClientIP());
				}
				String ip = "";
				for (String str : listIP) {
					ip += str + ";"; 
				}
				Platform.getServiceManager().getDbService().userinfoDao.upDateSDK(ip, id);
			}

		} else {
			if (AppConfig.logonStatus == 2) {
//				OperationResponse response = new OperationResponse(
//						operationRequest.OperationCode,
//						operationRequest.Parameters,
//						ReturnCode.NeedLicense, "");
//				session.SendOperationResponse(response);
			}
			
			Userinfo in = Platform.getServiceManager().getDbService().userinfoDao.Insert(id, id, new Date(),sdk,PhoneType,pwd);
			
			if (in != null) {
				
//				OperationResponse response = new OperationResponse(
//						operationRequest.OperationCode,
//						AppConfig.dicAppInfo, ReturnCode.Yes, "");
				
				returnCode = ServerResFlag.Yes_VALUE;
//				session.SendOperationResponse(response);
				
				PublicFunction.SetPlayerBehaviorPass(
						ConsumptionType.Online, session.getClientIP(),
						id);
				PublicFunction.SetPlayerBehaviorPass(
						ConsumptionType.GameSchedule,
						GameScheduleType.Logon.toString(), id);
				if (isGetIP.equals("1")) {
					String ip = "";
					ip = session.getClientIP() + ";";
					Platform.getServiceManager().getDbService().userinfoDao.upDateSDK(ip, id);
				}
			}
		}
		
		return returnCode;
    }

}
